package com.david.rocket.stream;

import com.david.rocket.common.Const;
import com.david.rocket.dao.GoodsRepository;
import com.david.rocket.dao.OrderRepository;
import com.david.rocket.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import static com.david.rocket.common.Const.TOPIC_ORDER_CREATE;

@Slf4j
@Component
@RocketMQMessageListener(topic = TOPIC_ORDER_CREATE, consumerGroup = "group-create")
class OrderCreateConsumer implements RocketMQListener<String> {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private GoodsRepository goodsRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void onMessage(String payload) {
        String[] s = payload.split("_");
        String orderId = s[0];
        String goodsId = s[1];
        log.info("orderId ===>" + orderId);
        //减库存
        goodsRepository.reduceStock(Long.valueOf(goodsId));
        log.info("reduce stock===>" + goodsId);
        //创建订单
        OrderEntity entity = new OrderEntity();
        entity.setStatus(Const.OrderStatue.paying.name());
        entity.setOrderId(orderId);
        entity.setGoodsId(Long.valueOf(goodsId));
        orderRepository.save(entity);
        log.info("save order ===>" + orderId);

    }
}
